package red.yancloud.www.ui.fragment


import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Rect
import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import kotlinx.android.synthetic.main.activity_main.*
import red.yancloud.www.R
import red.yancloud.www.base.BaseFragment
import red.yancloud.www.common.Constants
import red.yancloud.www.ui.activity.*
import red.yancloud.www.ui.adapter.SortRecyclerViewAdapter
import red.yancloud.www.util.ScreenUtils
import java.util.*


/**
 * @Org：www.shuhai.com(陕西书海网络科技有限公司)
 * @Author：风不会停息 on 2019/6/5 15:00
 * E_Mail：yh131412hys@163.com
 * Describe：分类
 * Change：
 * @Version：V1.0
 */
class SortFragment : BaseFragment(), View.OnClickListener {

    private lateinit var mainActivity:MainActivity

    override val layoutId: Int
        get() = R.layout.fragment_sort

    override fun onAttach(context: Context) {
        super.onAttach(context)

        mainActivity = context as MainActivity
    }

    override fun attachView() {
    }

    override fun initData() {

    }

    private fun getSortBeanList():List<SortBean> {
        val sortBeans = ArrayList<SortBean>()
        sortBeans.add(SortBean("延云阅读", "万卷书中  记录延安精神\n名家笔下  展现英雄风采"))
        sortBeans.add(SortBean("延云视听", "穿越时空  看先辈浴血奋战\n畅游沧海  论英雄自掂责任"))
        sortBeans.add(SortBean("红色文旅", "亲临圣地  重温峥嵘岁月\n走进延安  感受革命情怀"))
        sortBeans.add(SortBean("漫绘延安", "图文并茂  往事历历在目\n趣味盎然  英雄栩栩如生"))
//        sortBeans.add(SortBean("红歌会", "引颈高歌  齐赞山河故人\n代代相传  继承红色基因"))
        sortBeans.add(SortBean("去伪求真", "实事求是  探寻历史真相\n刨根问底  学习红色知识"))
        sortBeans.add(SortBean("红书包", "思想精髓  岂是一书能容\n读书万卷  只为牢记使命"))
        sortBeans.add(SortBean("红云专题", "不往初心  回味风雨历程\n砥砺前行  再走新的长征"))
        return sortBeans
    }

    class SortBean(var title: String?, var content: String?)

    @SuppressLint("InflateParams")
    override fun configView() {

//        val mDividerWidth = ScreenUtils.dip2px(mContext,10f)
        val mSortFragmentRV = parentView.findViewById<RecyclerView>(R.id.sortFragment_rV)
        mSortFragmentRV.layoutManager= GridLayoutManager(mContext,2,RecyclerView.VERTICAL,false)
//        mSortFragmentRV.addItemDecoration(GridSpacingItemDecoration(2, ScreenUtils.dip2px(mContext,10f),false))
//        mSortFragmentRV.addItemDecoration(object :RecyclerView.ItemDecoration(){
//
//            override fun getItemOffsets(
//                outRect: Rect,
//                view: View,
//                parent: RecyclerView,
//                state: RecyclerView.State
//            ) {
//                super.getItemOffsets(outRect, view, parent, state)
//
//                val itemPosition =
//                    (view.layoutParams as RecyclerView.LayoutParams).viewLayoutPosition
//                val spanCount: Int = getSpanCount(parent)
//                val childCount = parent.adapter!!.itemCount
//
//                val isLastRow: Boolean =
//                    isLastRow(parent, itemPosition, spanCount, childCount)
//                val isLastColumn =
//                    isLastColumn(parent, itemPosition, spanCount, childCount)
//
//                val left: Int
//                val right: Int
//                var bottom: Int
//                val eachWidth: Int = (spanCount - 1) * mDividerWidth / spanCount
//                val dl: Int = mDividerWidth - eachWidth
//
//                left = itemPosition % spanCount * dl
//                right = eachWidth - left
//                bottom = mDividerWidth
//                //Log.e("zzz", "itemPosition:" + itemPosition + " |left:" + left + " right:" + right + " bottom:" + bottom);
//                //Log.e("zzz", "itemPosition:" + itemPosition + " |left:" + left + " right:" + right + " bottom:" + bottom);
//                if (isLastRow) {
//                    bottom = 0
//                }
//                outRect.set(left, 0, right, bottom)
//            }
//        })
        val adapter = SortRecyclerViewAdapter(R.layout.item_sort_list)
        adapter.addHeaderView(LayoutInflater.from(mContext).inflate(R.layout.item_gridview_header, null))
        adapter.addData(getSortBeanList())
        mSortFragmentRV.adapter= adapter
        adapter.onItemClickListener = object : BaseQuickAdapter.OnItemClickListener{
            override fun onItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {

                when (position) {
                    0 -> {
                        /**
                         * 延云阅读
                         */
                        mainActivity.mainActivity_vP.currentItem= Constants.RedCloudMainType.MAIN_READ_VIEW
                    }
                    1 -> {
                        /**
                         * 延云视听
                         */
                        startActivity(Intent(mContext, VideoListActivity::class.java))
                    }
                    2 -> {
                        /**
                         * 革命纪念馆 RevolutionMemorial
                         * 红色文旅
                         */
                        startActivity(Intent(mContext, RedTravelActivity::class.java))
                    }
                    3 -> {
                        /**
                         * 漫绘延安
                         */
//                        startActivity(Intent(mContext, DiffuseYanAnActivity::class.java))
                        startActivity(Intent(mContext,NewsInfoActivity::class.java)
                            .putExtra("url","${Constants.API_BASE_RED_CLOUD_URL}Index/manhui.html")
                            .putExtra("model","")
                            .putExtra("id",""))
                    }
//                    6 -> {
//                        /**
//                         * 红歌会 RedSongMeet
//                         */
//                        ToastUtils.showLongToast("功能暂不开发。。。")
//                    }
                    4 -> {
                        /**
                         * 去伪求真（列表第一条大图）
                         */
                        startActivity(Intent(mContext, LookDummySeekTruthActivity::class.java))
                    }
                    5 -> {
                        /**
                         * 红书包（列表第一条大图）
                         */
                        startActivity(Intent(mContext,RedBagActivity::class.java))
                    }
                    6 -> {
                        /**
                         * 红云专题（列表第一条大图）
                         */
//                        startActivity(Intent(mContext,BroadcastMessageActivity::class.java).putExtra("type","红云专题"))
                        startActivity(Intent(mContext,SpecialTopicActivity::class.java))
                    }
                }
            }
        }
        adapter.headerLayout.setOnClickListener {

            /**
             * 延云知库
             */
            mainActivity.mainActivity_vP.currentItem= Constants.RedCloudMainType.MAIN_REPOSITORY_VIEW
        }

//        val gridView = parentView.findViewById<HeaderGridView>(R.id.sortFragment_gV)
//        gridView.addHeaderView(LayoutInflater.from(mContext).inflate(R.layout.item_gridview_header, null))
//        gridView.adapter= mContext?.let { SortGridViewAdapter(it,getSortBeanList()) }
//        gridView.onItemClickListener = object :AdapterView.OnItemClickListener{
//            override fun onItemClick(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
//
//                when (position) {
//                    0 -> {
//                        /**
//                         * 延云知库
//                         */
//                        mainActivity.mainActivity_vP.currentItem= Constants.RedCloudMainType.MAIN_REPOSITORY_VIEW
//                    }
//                    2 -> {
//                        /**
//                         * 延云阅读
//                         */
//                        mainActivity.mainActivity_vP.currentItem= Constants.RedCloudMainType.MAIN_READ_VIEW
//                    }
//                    3 -> {
//                        /**
//                         * 延云视听
//                         */
//                        startActivity(Intent(mContext, VideoListActivity::class.java))
//                    }
//                    4 -> {
//                        /**
//                         * 革命纪念馆 RevolutionMemorial
//                         * 红色文旅
//                         */
//                        startActivity(Intent(mContext, RedTravelActivity::class.java))
//                    }
//                    5 -> {
//                        /**
//                         * 漫绘延安
//                         */
//                        startActivity(Intent(mContext, DiffuseYanAnActivity::class.java))
////                        startActivity(Intent(mContext,NewsInfoActivity::class.java)
////                            .putExtra("url","http://www.yancloud.red/Yancloudapp/Index/manhui.html"))
//                    }
////                    6 -> {
////                        /**
////                         * 红歌会 RedSongMeet
////                         */
////                        ToastUtils.showLongToast("功能暂不开发。。。")
////                    }
//                    6 -> {
//                        /**
//                         * 去伪求真（列表第一条大图）
//                         */
//                        startActivity(Intent(mContext,LookDummySeekTruthActivity::class.java))
//                    }
//                    7 -> {
//                        /**
//                         * 红书包（列表第一条大图）
//                         */
//                        startActivity(Intent(mContext,RedBagActivity::class.java))
//                    }
//                    8 -> {
//                        /**
//                         * 红云专题（列表第一条大图）
//                         */
////                        startActivity(Intent(mContext,BroadcastMessageActivity::class.java).putExtra("type","红云专题"))
//                        startActivity(Intent(mContext,SpecialTopicActivity::class.java))
//                    }
//                }
//            }
//        }

//        parentView.findViewById<AppCompatImageView>(R.id.system_back).setOnClickListener(this)
//        parentView.findViewById<AppCompatImageView>(R.id.sortFragment_yanCloudRepository_iv).setOnClickListener(this)
//        parentView.findViewById<AppCompatImageView>(R.id.sortFragment_gameInterActive_iv).setOnClickListener(this)
//        parentView.findViewById<AppCompatImageView>(R.id.sortFragment_yanCloudRead_iv).setOnClickListener(this)
//        parentView.findViewById<AppCompatImageView>(R.id.sortFragment_featureEssay_iv).setOnClickListener(this)
//        parentView.findViewById<AppCompatImageView>(R.id.sortFragment_redHallCollect_iv).setOnClickListener(this)
//        parentView.findViewById<AppCompatImageView>(R.id.sortFragment_redCulturalTourism_iv).setOnClickListener(this)
//        parentView.findViewById<AppCompatImageView>(R.id.sortFragment_revolutionMemorial_iv).setOnClickListener(this)
//        parentView.findViewById<AppCompatImageView>(R.id.sortFragment_missionCenter_iv).setOnClickListener(this)
//        parentView.findViewById<AppCompatImageView>(R.id.sortFragment_yanCloudEnjoy_iv).setOnClickListener(this)
    }

    private fun isLastRow(
        parent: RecyclerView, pos: Int, spanCount: Int,
        childCount: Int
    ): Boolean {
        var childCount = childCount
        val layoutManager =
            parent.layoutManager
        if (layoutManager is GridLayoutManager) {
            // childCount = childCount - childCount % spanCount;

            val lines =
                if (childCount % spanCount == 0) childCount / spanCount else childCount / spanCount + 1
            return lines == pos / spanCount + 1
        } else if (layoutManager is StaggeredGridLayoutManager) {
            val orientation =
                layoutManager
                    .orientation
            // StaggeredGridLayoutManager 且纵向滚动


            if (orientation == StaggeredGridLayoutManager.VERTICAL) {
                childCount = childCount - childCount % spanCount
// 如果是最后一行，则不需要绘制底部
                if (pos >= childCount) return true
            } else {
                // 如果是最后一行，则不需要绘制底部

                if ((pos + 1) % spanCount == 0) {
                    return true
                }
            }
        }
        return false
    }

    private fun getSpanCount(parent: RecyclerView): Int {
        // 列数

        var spanCount = -1
        val layoutManager =
            parent.layoutManager
        if (layoutManager is GridLayoutManager) {
            spanCount =
                layoutManager.spanCount
        } else if (layoutManager is StaggeredGridLayoutManager) {
            spanCount = layoutManager
                .spanCount
        }
        return spanCount
    }

    private fun isLastColumn(
        parent: RecyclerView, pos: Int, spanCount: Int,
        childCount: Int
    ): Boolean {
        var childCount = childCount
        val layoutManager =
            parent.layoutManager
        if (layoutManager is GridLayoutManager) {
            if ((pos + 1) % spanCount == 0) {// 如果是最后一列，则不需要绘制右边

                return true
            }
        } else if (layoutManager is StaggeredGridLayoutManager) {
            val orientation =
                layoutManager
                    .orientation
            if (orientation == StaggeredGridLayoutManager.VERTICAL) {
                if ((pos + 1) % spanCount == 0)// 如果是最后一列，则不需要绘制右边
                {
                    return true
                }
            } else {
                childCount = childCount - childCount % spanCount
                if (pos >= childCount)// 如果是最后一列，则不需要绘制右边
                    return true
            }
        }
        return false
    }

    override fun onClick(v: View?) {
        when (v!!.id) {
//            R.id.system_back-> startActivity(Intent(mContext,MainActivity::class.java))
//            /**
//             * 延云知库
//             */
//            R.id.sortFragment_yanCloudRepository_iv -> startActivity(Intent(mContext,MainActivity::class.java))
//            /**
//             * 游戏互动
//             */
//            R.id.sortFragment_gameInterActive_iv-> startActivity(Intent(mContext,MainActivity::class.java))
//            /**
//             * 延云阅读
//             */
//            R.id.sortFragment_yanCloudRead_iv -> startActivity(Intent(mContext,MainActivity::class.java))
//            /**
//             * 专题文汇
//             */
//            R.id.sortFragment_featureEssay_iv-> startActivity(Intent(mContext,MainActivity::class.java))
//            /**
//             * 红馆珍藏
//             */
//            R.id.sortFragment_redHallCollect_iv -> startActivity(Intent(mContext,MainActivity::class.java))
//            /**
//             * 红色文旅
//             */
//            R.id.sortFragment_redCulturalTourism_iv-> startActivity(Intent(mContext,MainActivity::class.java))
//            /**
//             * 革命纪念馆
//             */
//            R.id.sortFragment_revolutionMemorial_iv -> startActivity(Intent(mContext,MainActivity::class.java))
//            /**
//             * 宣教中心
//             */
//            R.id.sortFragment_missionCenter_iv-> startActivity(Intent(mContext,MainActivity::class.java))
//            /**
//             * 延云享乐
//             */
//            R.id.sortFragment_yanCloudEnjoy_iv -> startActivity(Intent(mContext,MainActivity::class.java))
        }
    }
}
